package org.dding.core.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 占位符替换工具类
 * 
 */
public class PlaceholderUtils {

	private Properties globalProperties = new Properties();

	private static List<String> loadedProperties = new ArrayList<String>();

	private static final PlaceholderUtils instance = new PlaceholderUtils();

	private PlaceholderUtils() {
	}

	private void loadProperties(Properties prop) {
		globalProperties.putAll(prop);
	}

	public static PlaceholderUtils getInstance() {
		return instance;
	}

	/**
	 * 装载一个全局配置文件
	 * 
	 * @param filename
	 *            properties file name
	 * @return PlaceHolderUtil
	 * @throws IOException
	 *             if failed to load property file
	 */
	public static PlaceholderUtils loadGlobalProperty(String filename)
			throws IOException {
		if (!loadedProperties.contains(filename)) {
			InputStream in = PlaceholderUtils.class.getClassLoader()
					.getResourceAsStream(filename);
			if (in != null) {
				Properties prop = new Properties();
				prop.load(in);
				in.close();
				instance.loadProperties(prop);
				loadedProperties.add(filename);
			} else {
				throw new FileNotFoundException(filename);
			}
		}
		return instance;
	}
}